package org.demo.transactional.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.demo.transactional.common.Result;
import org.demo.transactional.domain.User;
import org.demo.transactional.service.IUserMapperService;
import org.demo.transactional.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class MybatisController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserMapperService userMapperService;

    @RequestMapping(value="/list", method= RequestMethod.GET)
    public List<User> getUsers(){
        return userService.findUserList();
    }

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUserById(@PathVariable("id")long id){
        return userService.findUserById(id);
    }

    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public Result deleteUserById(@PathVariable("id") long id){
        int i =  userService.delete(id);
        if(i == 1 ){
            return Result.success().setData(i);
        }else {
            return Result.fail();
        }
    }
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public Result updateUser(@PathVariable("id")long id,
                             @RequestParam(value="name", required = true) String name,
                             @RequestParam(value="age", required = true) int age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setId(id);
        int i = userService.update(user);
        if(i == 1 ){
            return Result.success().setData(i);
        }else {
            return Result.fail();
        }
    }

    @RequestMapping(value="", method=RequestMethod.POST)
    public Result postUser(@RequestParam(value="name") String name,
                           @RequestParam(value="age") int age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        int i = userService.add(user);
        if(i == 1 ){
            return Result.success().setData(i);
        }else {
            return Result.fail();
        }
    }

    @RequestMapping(value="/addList", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result updateUserList(@RequestBody String userList){
        List<User> users = JSON.parseArray(userList, User.class);
        try {
            int count = userMapperService.addUser(users);
            return Result.success().setData(count);
        }catch(Exception  ex){
            log.info(ex.getMessage(), ex);
            return Result.fail().setData(ex.getMessage());
        }
    }
}
